package jinyilw.tools.video;

import jinyilw.tools.video.jin2mov.DefaultMovieInfoProvider;
import jinyilw.tools.video.jin2mov.FrameSavedListener;
import jinyilw.tools.video.jin2mov.Jim2Mov;
import jinyilw.tools.video.jin2mov.MovieInfoProvider;
import jinyilw.tools.video.jin2mov.MovieSaveException;
import jinyilw.tools.video.jin2mov.MovieUtils;

import javax.media.MediaLocator;
import java.io.File;
import java.io.IOException;

public class VideoTools
{
	private static DefaultFrameSavedListener defaultFrameSavedListener;

	private VideoTools()
	{
	}

	public static void createMp4Video(String videoLocation, int width,
			int height, int length, int fps, final ImageCreator imageCreator)
	{
		if (!videoLocation.endsWith("mp4"))
			videoLocation += ".mp4";
		DefaultMovieInfoProvider dmip = new DefaultMovieInfoProvider(
				createMediaLocator(videoLocation));
		dmip.setMWidth(width);
		dmip.setMHeight(height);
		dmip.setNumberOfFrames(length);
		dmip.setFPS(fps);
		try
		{
			new Jim2Mov(frame -> {
				try
				{
					return MovieUtils.bufferedImageToJPEG(
							imageCreator.createBufferedImage(frame), 1.0f);
				} catch (IOException e)
				{
					e.printStackTrace();
				}
				return null;
			}, dmip, null).saveMovie(MovieInfoProvider.TYPE_QUICKTIME_JPEG);
		} catch (MovieSaveException e)
		{
			e.printStackTrace();
		}
	}

	public static void pictureToMp4Video(final File[] picFiles,
			String videoLocation, int width, int height, int fps)
	{
		if (!videoLocation.endsWith("mp4"))
			videoLocation += ".mp4";
		DefaultMovieInfoProvider dmip = new DefaultMovieInfoProvider(
				createMediaLocator(videoLocation));
		dmip.setMWidth(width);
		dmip.setMHeight(height);
		dmip.setNumberOfFrames(picFiles.length);
		dmip.setFPS(fps);
		try
		{
			new Jim2Mov(frame -> {
				try
				{
					return MovieUtils.convertImageToJPEG(picFiles[frame],
							1.0f);
				} catch (IOException e)
				{
					e.printStackTrace();
				}
				return null;
			}, dmip, getDefaultFrameSavedListener())
					.saveMovie(MovieInfoProvider.TYPE_QUICKTIME_JPEG);
		} catch (MovieSaveException e)
		{
			e.printStackTrace();
		}
	}

	public static MediaLocator createMediaLocator(String url)
	{
		if (url == null)
			return null;
		if (url.startsWith("file:"))
			return new MediaLocator(url);
		else
			return new MediaLocator("file:" + url);
	}

	public static DefaultFrameSavedListener getDefaultFrameSavedListener()
	{
		if (defaultFrameSavedListener == null)
			defaultFrameSavedListener = new DefaultFrameSavedListener();
		return defaultFrameSavedListener;
	}

	static class DefaultFrameSavedListener implements FrameSavedListener
	{
		@Override
		public void frameSaved(int frameNumber)
		{
			System.out.println("Saved frame: " + frameNumber);
		}
	}
}
